package com.geek.framework.study.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

public interface ServiceLoaderUtils {


    static <T> List<T> loadSPI(Class<T> tClass) {
        return loadSPI(tClass, Thread.currentThread().getContextClassLoader());
    }


    static <T> List<T> loadSPI(Class<T> tClass, ClassLoader classLoader) {
        List<T> result = new ArrayList<>();

        ServiceLoader<T> serviceLoader = ServiceLoader.load(tClass, classLoader);
        Iterator<T> iterator = serviceLoader.iterator();
        while (iterator.hasNext()) {
            result.add(iterator.next());
        }
        return result;
    }


    static <T> T loadFirstSPI(Class<T> tClass) {
        return loadFirstSPI(tClass, Thread.currentThread().getContextClassLoader());
    }

    static <T> T loadFirstSPI(Class<T> tClass, ClassLoader classLoader) {
        ServiceLoader<T> serviceLoader = ServiceLoader.load(tClass, classLoader);
        Iterator<T> iterator = serviceLoader.iterator();
        while (iterator.hasNext()) {
            return iterator.next();
        }
        return null;
    }


}
